package com.topisv.tms.mybatis.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.topisv.tms.mybatis.Pagination;
import com.topisv.tms.mybatis.RowBoundsExt;
import com.topisv.tms.mybatis.SqlMapDao;
import com.topisv.tms.utils.ContextHolderUtils;
import com.topisv.tms.utils.PubUtil;

/**
 * mybatis公用类
 * @author  Fisher
 * @version  [v1.0.1, 2016年7月11日]
 */
@Service
public class CommonService{
    
    @Autowired
    public SqlMapDao sqlMapDao;
    
    /**
     * mybatis 的分页查询
     * @param countStatement 用于统计数量的sql
     * @param queryStatement 用于查询的sql
     * @param param 查询参数
     * @param request 分页信息
     * @param clazz 转化的类
     * @return 分页对象
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    public Pagination myBatisPage(String countStatement, String queryStatement, Object param, Class clazz) {
        RowBoundsExt rowBounds = this.getRowBounds();
        int count = (Integer)sqlMapDao.selectOne(countStatement, param);
        Pagination page = new Pagination(rowBounds, count);
        List list = sqlMapDao.selectList(queryStatement, param, rowBounds);
        PubUtil.convertListMapToObject(list, clazz);
        page.setAaData(list);
        return page;
    }
    
    /**
     * mybatis 的分页查询
     * @param countStatement    用于统计数量的sql
     * @param queryStatement    用于查询的sql
     * @param param 查询参数
     * @return 分页对象
     */
    public Pagination myBatisPage(String countStatement, String queryStatement, Object param) {
        
        RowBoundsExt rowBounds = this.getRowBounds();
        int count = (Integer)sqlMapDao.selectOne(countStatement, param);
        Pagination page = new Pagination(rowBounds, count);
        List list = sqlMapDao.selectList(queryStatement, param, rowBounds);
        
        page.setAaData(list);
        return page;
    }
    
    /**
     * 能过request获取表格的请求页数对象
     */
    public RowBoundsExt getRowBounds() {
        HttpServletRequest request = ContextHolderUtils.getRequest();
        RowBoundsExt rowBounds;
        if(request != null) {
            Integer offset = request.getParameter("iDisplayStart") != null ? Integer.valueOf(request.getParameter("iDisplayStart")) : 0;
            Integer limit = request.getParameter("iDisplayLength") != null ? Integer.valueOf(request.getParameter("iDisplayLength")) : 20;
            rowBounds = new RowBoundsExt(offset, limit);
        }else {
            rowBounds = new RowBoundsExt(0, 10);
        }
        return rowBounds;
    }
	
}
